<template>
  <div class="app-container">
    <div>
      <div style="display: flex" :gutter="10">
        <div style="flex: 1">
          <el-button
            @click="gobackWay"
            type="text"
            icon="el-icon-arrow-left"
            style="color: rgba(0, 0, 0, 0.85)"
            >返回</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <span>签到记录</span>
        </div>
      </div>
      <div style="padding:20px 20px 5px 20px">
      <el-form :inline="true" class="search-form">
        <div class="flex-between">
          <div>
            <el-form-item label="活动名称" class="search-form-item" prop="activity_name">
              <el-input clearable placeholder="请输入活动名称" v-model="searchForm.sign_name">
              </el-input>
            </el-form-item>
            <el-form-item label="生效区域" class="search-form-item" prop="region">
              <el-cascader filterable v-model="searchForm.appoint_area_select" style="width: 100%" :options="regionList"
                collapse-tags :props="{
                expandTrigger: 'hover',
                multiple: true,
                value: 'id',
                label: 'name',
                children: 'children',
                checkStrictly: false,
                emitPath: false,
              }" clearable></el-cascader>
            </el-form-item>
            <el-form-item label="用户群组" class="search-form-item" prop="group">
              <el-select clearable v-model="searchForm.user_group" multiple collapse-tags placeholder="请选择用户群组">
                <el-option v-for="item in groupingList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="活动状态" class="search-form-item" prop="status">
              <el-select clearable v-model="searchForm.status" placeholder="请选择状态">
                <el-option v-for="item in status" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" class="search-form-item" prop="time">
              <el-date-picker v-model="searchForm.time" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right" clearable>
              </el-date-picker>
            </el-form-item>
          </div>
          <div class="button-box">
            <el-button @click="getListWay" type="primary" icon="el-icon-search"
              class="inquire-box marginBottom-10">查询</el-button>
            <el-button icon="el-icon-refresh-left" class="reset-box" @click="resetting('searchForm')">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    </div>
    <el-divider></el-divider>
    <div style="margin-top: 20px">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- <el-button
            v-hasPermi="'raffle/save'"
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="saveWay"
            >新建</el-button
          > -->
        </el-col>
        <el-col :span="8" style="float: right">
          <div class="right-panel el-button-group">
            <el-button
              class=""
              icon="el-icon-refresh"
              size="mini"
              @click="resetting"
            ></el-button>
            <el-dropdown trigger="click" :hide-on-click="false">
              <span class="el-dropdown-link">
                <el-button
                  class=""
                  icon="el-icon-s-operation"
                  size="mini"
                ></el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="fruit in allTableThead" :key="fruit">
                  <el-checkbox v-model="checkboxTableThead" :label="fruit">{{
                    tableTheadOptions[fruit].label
                  }}</el-checkbox>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-col>
      </el-row>
      <el-col class="marginTop">
        <el-table
          v-loading="loading"
          highlight-current-row
          :data="dataList"
          :header-cell-style="{
            'background-color': '#f3f8fe',
            color: '#606266',
            height: '50px',
          }"
          style="width: 100%"
        >
          <el-table-column
            v-for="fruit in tableThead"
            :key="fruit"
            :label="tableTheadOptions[fruit].label"
            min-width="80"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="fruit == 'reward_type'">
                <el-tag
                  size="mini"
                  style="margin: 5px"
                  v-for="(item, index) in scope.row.reward_type"
                  :key="index"
                  type="primary"
                  >{{ item == 1 ? "积分" : "抽奖次数" }}</el-tag
                >
              </div>
              <div v-else>
                {{ scope.row[fruit] }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="lottery_num" label="奖励积分" align="center">
          </el-table-column>
          <el-table-column prop="integral_num" label="奖励提货劵" align="center">
          </el-table-column>
          <el-table-column prop="integral_num" label="奖励积分转换卡" align="center">
          </el-table-column>
        </el-table>
      </el-col>
    </div>


  </div>
</template>

<script>
import {
  SaveSignRule,
  getSignRuleInfo,
  getSignRuleList,
  delSignRule,
} from "@/api/activity/index";
import {
  getgroupList,
  getTagCategoryAll,
  getgradeList,
  getRegionList,
} from "@/api/user/index";
const tableTheadOption = {
  id: {
    label: "ID",
    field: "id",
  },
  sign_id: {
    label: "签到ID",
    field: "sign_id",
  },

  updated_at: {
    label: "更新时间",
    field: "updated_at",
  },
  sing_day: {
    label: "连续签到天数",
    field: "sing_day",
  },
  reward_type: {
    label: "奖励类型",
    field: "reward_type",
  },
};
const allTableThead = [
  "id",
  "sign_id",
  "updated_at",
  "sing_day",
  "reward_type",
];
const defaultTableThead = ["id", "sing_day", "reward_type",];

export default {
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1;
    },
  },
  data() {
    return {
      // 动态显示表头默认表头
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
      tableKey: 1, // 为了保证table 每次都会重渲
      loading: false,
      regionList: [],//生效区域
      groupingList: [],//用户群组
      status: [
        { name: "已过期", id: -1 },
        { name: "已开启", id: 1 },
        { name: "进行中", id: 3 },
        { name: "已关闭", id: 2 },
      ],
      searchForm: {
        id: "",
        page: 1,
        count: 10,
        sign_name: "",// 签到活动名称
        status: "",// 状态状态：-1过期 1开启 2进行中 3关闭
        appoint_area_select: [], //生效区域
        user_group: [], //用户群组
        time: [], //创建时间
      },
      id: "", // 当前编辑的规则id
      dataList: [],
      total: 0,
      saveLoaidng: false,
      saveVisible: false,
      title: "",
      saveForm: {
        id: "",
        rule: [
          {
            id: 0,
            sing_day: "",
            reward_type: [1],
            lottery_num: 0,
            integral_num: 0,
          },
        ],
      },
      sing_day: (rule, value, callback) => {
        let req = /\D/g;
        if (value === "") {
          callback(new Error("请输入连续签到天数"));
        } else {
          if (req.test(value)) {
            callback(new Error("连续签到天数只能为数字,且只能是整数"));
          } else {
            callback();
          }
        }
      },
      reward_type: (rule, value, callback) => {
        if (value.length == 0) {
          callback(new Error("请选择奖励类型"));
        } else {
          callback();
        }
      },
      integral_num: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入积分数量"));
        } else {
          let req = /^\d+(\.\d{1,2})?$/;
          if (req.test(value)) {
            callback();
          } else {
            callback(new Error("只能输入数字,且只能保留两位小数"));
          }
        }
      },
      lottery_num: (rule, value, callback) => {
        let req = /\D/g;
        if (value === "") {
          callback(new Error("请输入抽奖次数"));
        } else {
          if (req.test(value)) {
            callback(new Error("抽奖次数只能为数字,且只能是整数"));
          } else {
            callback();
          }
        }
      },
    };
  },
  created() {
    this.searchForm.id = this.$route.query.pId;
    const p1 = new Promise((resolve, reject) => {
      getgroupList().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.groupingList = res.data.list;
        resolve();
      });
    });

    const p2 = new Promise((resolve, reject) => {
      getTagCategoryAll().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.TagCategoryAll = res.data;
        resolve();
      });
    });

    const p3 = new Promise((resolve, reject) => {
      getgradeList().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.gradeList = res.data.list;
        resolve();
      });
    });
    const p4 = new Promise((resolve, reject) => {
      getRegionList({ level: 2 }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          reject();
          return;
        }
        this.regionList = res.data;
        console.log(this.regionList)
        resolve();
      });
    });
    Promise.all([p1, p2, p3, p4])
      .then(() => {
        this.getListWay();
      })
      .catch(() => {
        this.loading = false;
      });





  },
  methods: {
    getListWay() {
      this.loading = true;
      getSignRuleList(this.searchForm).then((res) => {
        this.loading = false;
        if (res.code !== 200 || res.status !== 1) {
          this.loading = false;
          return this.$messages.error(res.msg);
        }
        res.data.forEach((item) => {
          item.reward_type = item.reward_type.split(",");
        });
        this.dataList = res.data;
        this.total = res.data.total;
      });
    },
    resetting() {
      this.searchForm = {
        id: this.$route.query.pId,
      };
      this.getListWay();
    },

    saveClose() {
      this.saveForm.id = "";
      this.saveForm.rule = [
        {
          id: 0,
          sing_day: "",
          reward_type: [1],
          lottery_num: 0,
          integral_num: 0,
        },
      ];
      this.id = "";
    },

    saveWay() {
      this.title = "添加规则";
      this.saveVisible = true;
    },
    addrule_section() {
      this.saveForm.rule.push({
        id: this.saveForm.rule.length + "" + new Date().getTime(),
        sing_day: "",
        reward_type: [1],
        lottery_num: 0,
        integral_num: 0,
      });
    },
    delRuleWay(row) {
      var arr = [];
      this.saveForm.rule.forEach((item) => {
        if (item.id !== row.id) {
          arr.push(item);
        }
      });
      this.saveForm.rule = arr;
    },
    integral_numFocus(item) {
      if (item.integral_num == 0) {
        item.integral_num = "";
      }
    },
    integral_numBlur(item) {
      if (item.integral_num == "") {
        item.integral_num = 0;
      }
    },
    lottery_numFocus(item) {
      if (item.lottery_num == 0) {
        item.lottery_num = "";
      }
    },
    lottery_numBlur(item) {
      if (item.lottery_num == "") {
        item.lottery_num = 0;
      }
    },
    saveSubmit() {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          var obj = {
            id: this.saveForm.id,
            sign_id: this.searchForm.id,
            rule: JSON.parse(JSON.stringify(this.saveForm.rule)),
          };
          let forData = [];
          for (let i = 0; i < obj.rule.length; i++) {
            if (!forData.some((e) => e.sing_day == obj.rule[i].sing_day))
              forData.push(obj.rule[i]);
          }
          if (forData.length !== obj.rule.length) {
            return this.$messages.error("有重复的签到天数");
          }

          obj.rule.forEach((item) => {
            item.reward_type = item.reward_type.toString();
          });
          obj.rule = JSON.stringify(obj.rule);
          this.saveLoaidng = true;
          SaveSignRule(obj).then((res) => {
            this.saveLoaidng = false;
            if (res.code !== 200 || res.status !== 1) {
              return this.$messages.error(res.msg);
            }
            this.$messages.success(res.msg);
            this.saveClose();
            this.saveVisible = false;
            this.getListWay();
          });
        } else {
          return false;
        }
      });
    },
    gobackWay() {
      this.$router.push("/activity/signin");
    },
  },
};
</script>

<style>
</style>
